package com.zk.lettcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 * 最初的想法：暴力拆解，遍历数组，使用目标数减去当前位，拿差值再去数组中查找是否存在
 * 实现方式：根据hashMap方式快速查找
 * @Author: zhang kai
 * @Date: 2021/11/08
 * @Description: https://leetcode-cn.com/problems/two-sum/
 */
public class Practice2 {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            int val = target - nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                if (val == nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }
    public int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{i, map.get(target - nums[i])};
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }
}
